import React, { useState, useRef, useEffect, useImperativeHandle, forwardRef } from 'react'
import { lazy } from 'ice'
import EntityTitleDom from './components/EntityTitleDom'
import { Button, Search } from '@alifd/next'
import { useMemoizedFn, useCreation } from 'ahooks'
import { translate, isLayerExist } from '@/utils/tools'
import store from '@/store'
import styles from './index.module.scss'
import { isEqual } from 'lodash-es'

const TreeDom = lazy(() => import('@/components/TreeDom'))

const Entity = ({}, ref) => {
  const [graphState, graphDispatchers] = store.useModel('graph')
  const { stage, data } = graphState

  const [treeType] = useState('entity')

  const [but0, setBut0] = useState({ className: styles.switchDisabledButton, disabled: true })
  const [but1, setBut1] = useState({ className: styles.switchDisabledButton, disabled: true })

  const but0Ref = useRef()
  const but1Ref = useRef()

  useEffect(() => {
    but0Ref.current = but0
  }, [but0])

  useEffect(() => {
    but1Ref.current = but1
  }, [but1])

  useEffect(() => {
    const newbut0 = getClassName('mainwall', stage, 0)
    const newbut1 = getClassName('mainwall', stage, 1)
    if (!isEqual(newbut0, but0Ref.current)) setBut0(newbut0)
    if (!isEqual(newbut1, but1Ref.current)) setBut1(newbut1)
    // eslint-disable-next-line no-use-before-define
  }, [data, stage, getClassName])

  const layerTreeRef = useRef()
  const blockTreeRef = useRef()

  const onSearch = useMemoizedFn(value => {
    layerTreeRef.current.onSearch(value)
    blockTreeRef.current.onSearch(value)
  })

  const createKeyTitle = useMemoizedFn(({ name, fatherId, treeKey, arr, idToEye, onlyToEye, setEye }) => {
    return (
      <EntityTitleDom
        name={name}
        fatherId={fatherId}
        arr={arr}
        treeKey={treeKey}
        idToEye={idToEye}
        treeType={treeType}
        onlyToEye={onlyToEye}
        setEye={setEye}
      />
    )
  })

  const getClassName = useMemoizedFn((key, stage, sign) => {
    const disabled = !isLayerExist(key, data)
    if (disabled) return { className: styles.switchDisabledButton, disabled }
    if (stage.includes('concrete')) {
      if (sign === 0) {
        return { className: styles.switchUnSelectedButton, disabled }
      } else {
        return { className: styles.switchSelectedButton, disabled }
      }
    } else {
      if (sign === 0) {
        return { className: styles.switchSelectedButton, disabled }
      } else {
        return { className: styles.switchUnSelectedButton, disabled }
      }
    }
  })

  useImperativeHandle(ref, () => ({
    setEye: arg => {
      const { ids: layerIds, keys: layerKeys } = layerTreeRef.current.setEye(arg)
      const { ids: blockIds, keys: blockKeys } = blockTreeRef.current.setEye(arg)
      return { ids: [...layerIds, ...blockIds], keys: { ...layerKeys, ...blockKeys } }
    }
  }))

  const initObjArr = useCreation(
    () => [
      {
        entity: {
          layer: { polyline: {}, arc: {}, ellipse: {}, circle: {}, text: {}, line: {}, solid: {} }
        }
      },
      {
        entity: {
          block: { polyline: {}, arc: {}, ellipse: {}, circle: {}, text: {}, line: {}, solid: {} }
        }
      }
    ],
    []
  )

  return (
    <div className={styles.Entity}>
      <div className={styles.switch}>
        <div className={but0.className}>
          <Button
            className={styles.button}
            ghost={'dark'}
            type={'normal'}
            text
            disabled={but0.disabled}
            onClick={() => graphDispatchers.update({ stage: ['masonry', 'plaster'] })}
          >
            {['masonry', 'plaster'].map(i => translate(i)).join(' \\ ')}
          </Button>
        </div>
        <div className={but1.className}>
          <Button
            className={styles.button}
            ghost={'dark'}
            type={'normal'}
            text
            disabled={but1.disabled}
            onClick={() => graphDispatchers.update({ stage: ['concrete'] })}
          >
            {['concrete'].map(i => translate(i)).join(' \\ ')}
          </Button>
        </div>
      </div>
      <div className={styles.search}>
        <Search
          style={{ width: '100%', height: ' 100%' }}
          shape="simple"
          type="normal"
          placeholder="Search"
          onChange={onSearch}
        />
      </div>
      <div className={styles.tree}>
        <div style={{ width: '100%', height: '100%', overflow: 'auto' }}>
          <TreeDom ref={layerTreeRef} treeType={treeType} createKeyTitle={createKeyTitle} initObj={initObjArr[0]} />
          <div style={{ width: '100%', height: '2px', backgroundColor: '#2e3440', margin: '2px 0px 2px 0px' }} />
          <TreeDom ref={blockTreeRef} treeType={treeType} createKeyTitle={createKeyTitle} initObj={initObjArr[1]} />
        </div>
      </div>
    </div>
  )
}

export default forwardRef(Entity)
